import { defineStore } from 'pinia'

const buildSessionId = (sellerId, itemId = '') => {
  const seller = String(sellerId || '').trim()
  const item = String(itemId || '').trim()
  return item ? `${seller}#${item}` : seller
}

const initialFloatingPosition = {
  right: 24,
  bottom: 120
}

const useChatStore = defineStore('globalChat', {
  state: () => ({
    visible: false,
    selectedClientId: '',
    currentSessionId: '',
    sessions: [],
    messages: {},
    unreadCount: 0,
    floatingPosition: { ...initialFloatingPosition }
  }),

  getters: {
    hasSelectedClient: (state) => Boolean(state.selectedClientId),
    currentSession(state) {
      if (!state.currentSessionId) return null
      return state.sessions.find((item) => item.sessionId === state.currentSessionId) || null
    },
    currentMessages(state) {
      if (!state.currentSessionId) return []
      return state.messages[state.currentSessionId] || []
    }
  },

  actions: {
    toggleVisible() {
      this.visible = !this.visible
      if (this.visible) this.resetUnread()
    },

    setVisible(visible) {
      this.visible = visible
      if (visible) this.resetUnread()
    },

    selectClient(clientId) {
      this.selectedClientId = clientId || ''
    },

    setSessions(list) {
      this.sessions = Array.isArray(list) ? [...list] : []
      if (this.currentSessionId) {
        const exists = this.sessions.find((item) => item.sessionId === this.currentSessionId)
        if (!exists) this.currentSessionId = ''
      }
    },

    addOrUpdateSession(session) {
      if (!session) return
      // ✅ 优先使用传入的sessionId（可能包含chat_id），如果没有则使用buildSessionId构建
      const sessionId = session.sessionId || buildSessionId(session.sellerId || session.seller_id, session.itemId || session.item_id)
      if (!sessionId) return

      // ✅ 查找现有会话：优先使用sessionId精确匹配，如果没有找到，再尝试用sellerId和itemId查找（兼容旧数据）
      let index = this.sessions.findIndex((item) => item.sessionId === sessionId)
      let existingSession = index !== -1 ? this.sessions[index] : null
      
      // ✅ 如果没找到，尝试用sellerId和itemId查找（兼容旧数据，可能使用不同的conversation_id格式）
      if (index === -1 && (session.sellerId || session.seller_id) && (session.itemId || session.item_id)) {
        const fallbackSessionId = buildSessionId(session.sellerId || session.seller_id, session.itemId || session.item_id)
        if (fallbackSessionId && fallbackSessionId !== sessionId) {
          index = this.sessions.findIndex((item) => item.sessionId === fallbackSessionId)
          if (index !== -1) {
            existingSession = this.sessions[index]
            // ✅ 更新现有会话的sessionId为新的sessionId（使用conversation_id或chat_id）
            existingSession.sessionId = sessionId
          }
        }
      }

      // ✅ 构建更新数据：如果字段存在则使用新值，否则保留原有值
      // ⚠️ 重要：使用 !== undefined 而不是 ||，避免空字符串被视为falsy
      const payload = {
        sessionId,
        sellerId: session.sellerId || session.seller_id || existingSession?.sellerId || '',
        // ✅ 改进：优先使用新值，即使是空字符串（允许清空错误值）
        sellerName: (session.sellerName !== undefined ? session.sellerName : (session.seller_name !== undefined ? session.seller_name : existingSession?.sellerName)) || '未知卖家',
        itemId: session.itemId || session.item_id || existingSession?.itemId || '',
        // ✅ 商品信息：如果新数据中没有，保留原有数据
        itemTitle: session.itemTitle !== undefined ? session.itemTitle : (session.item_title !== undefined ? session.item_title : existingSession?.itemTitle),
        itemPrice: session.itemPrice !== undefined ? session.itemPrice : (session.item_price !== undefined ? session.item_price : existingSession?.itemPrice),
        itemImage: session.itemImage !== undefined ? session.itemImage : (session.item_image !== undefined ? session.item_image : existingSession?.itemImage),
        itemTags: session.itemTags !== undefined ? session.itemTags : (session.item_tags !== undefined ? session.item_tags : (existingSession?.itemTags || [])),
        itemStatus: session.itemStatus !== undefined ? session.itemStatus : (session.item_status !== undefined ? session.item_status : existingSession?.itemStatus),
        itemStatusStr: session.itemStatusStr !== undefined ? session.itemStatusStr : (session.item_status_str !== undefined ? session.item_status_str : existingSession?.itemStatusStr),
        // ✅ 商品详情（包含图片和视频信息，用于媒体查看器）
        itemDetail: session.itemDetail !== undefined ? session.itemDetail : existingSession?.itemDetail || null,
        // ✅ 头像：如果传入了avatar字段且不为空，则使用；否则保留原值
        avatar: (session.avatar !== undefined && session.avatar !== null && session.avatar !== '') ? session.avatar : (existingSession?.avatar || ''),
        // ✅ 消息和时间：优先使用新值
        lastMessage: session.lastMessage !== undefined ? session.lastMessage : existingSession?.lastMessage || '',
        lastTime: session.lastTime !== undefined ? session.lastTime : existingSession?.lastTime || new Date().toISOString(),
        // ✅ 未读数：如果新数据中有则使用，否则保留原有
        unread: session.unread !== undefined ? session.unread : (existingSession?.unread ?? 0)
      }

      if (index !== -1) {
        // ✅ 更新现有会话：合并原有数据和新数据
        this.sessions.splice(index, 1, { ...existingSession, ...payload })
      } else {
        // ✅ 创建新会话
        this.sessions.unshift(payload)
      }

      // ✅ 移除自动切换会话的逻辑，避免收到消息时自动切换到其他会话
      // 只有用户主动点击会话时才切换（通过 handleSelectSession）
      // if (!this.currentSessionId) {
      //   this.currentSessionId = sessionId
      // }
    },

    setCurrentSession(sessionId) {
      this.currentSessionId = sessionId || ''
    },

    setMessages(sessionId, messageList = []) {
      if (!sessionId) return
      this.messages[sessionId] = Array.isArray(messageList) ? [...messageList] : []
    },

    appendMessages(sessionId, messageList = []) {
      if (!sessionId || !Array.isArray(messageList) || !messageList.length) return
      if (!this.messages[sessionId]) {
        this.messages[sessionId] = []
      }
      
      // ✅ 去重逻辑：避免重复添加相同的消息
      const existingIds = new Set(
        this.messages[sessionId].map(m => m.messageId || m.localId).filter(Boolean)
      )
      
      const newMessages = messageList.filter(msg => {
        const msgId = msg.messageId || msg.localId
        if (!msgId) return true // 如果没有ID，保留（可能是系统消息）
        if (existingIds.has(msgId)) {
          // ✅ 如果消息已存在，检查是否需要更新（例如：用真实消息替换乐观更新的消息）
          const existingIndex = this.messages[sessionId].findIndex(
            m => (m.messageId || m.localId) === msgId
          )
          if (existingIndex !== -1) {
            const existing = this.messages[sessionId][existingIndex]
            // 如果已存在的消息是乐观更新的（有localId但没有messageId），用真实消息替换
            if (existing.localId && !existing.messageId && msg.messageId) {
              this.messages[sessionId][existingIndex] = msg
              return false // 已替换，不重复添加
            }
          }
          return false // 已存在且不需要更新，跳过
        }
        return true // 新消息，添加
      })
      
      if (newMessages.length > 0) {
        // ✅ 创建新数组引用，确保 Vue 响应式更新
        const currentMessages = this.messages[sessionId] || []
        const updatedMessages = [...currentMessages, ...newMessages]
        // ✅ 添加新消息后，按时间正序排序（确保消息顺序正确）
        updatedMessages.sort((a, b) => {
          const timeA = new Date(a.message_time || a.timestamp || 0).getTime()
          const timeB = new Date(b.message_time || b.timestamp || 0).getTime()
          return timeA - timeB
        })
        // ✅ 使用新数组引用，确保响应式更新
        this.messages[sessionId] = updatedMessages
      }
    },

    prependMessages(sessionId, messageList = []) {
      if (!sessionId || !Array.isArray(messageList) || !messageList.length) return
      if (!this.messages[sessionId]) {
        this.messages[sessionId] = []
      }
      this.messages[sessionId] = [...messageList, ...this.messages[sessionId]]
    },

    removeMessage(sessionId, messageIdOrLocalId) {
      if (!sessionId || !messageIdOrLocalId) return
      const list = this.messages[sessionId]
      if (!list) return
      const index = list.findIndex(m => m.messageId === messageIdOrLocalId || m.localId === messageIdOrLocalId)
      if (index !== -1) {
        list.splice(index, 1)
      }
    },

    clearMessages(sessionId) {
      if (!sessionId) return
      this.messages[sessionId] = []
    },

    addMessage(message) {
      if (!message) return
      const sessionId = buildSessionId(message.seller_id, message.item_id)
      if (!sessionId) return

      // 确保会话存在
      this.addOrUpdateSession({
        sellerId: message.seller_id,
        sellerName: message.seller_name,
        itemId: message.item_id,
        itemTitle: message.item_title,
        lastMessage: message.content,
        lastTime: message.timestamp
      })

      // 添加消息
      const msg = {
        messageId: message.message_id,
        direction: message.direction,
        message_content: message.content,
        message_time: message.timestamp,
        message_type: message.message_type
      }
      this.appendMessages(sessionId, [msg])
    },

    /**
     * 通过 tempId 查找消息
     */
    findMessageByTempId(sessionId, tempId) {
      if (!sessionId || !tempId) return null
      const msgList = this.messages[sessionId]
      if (!msgList) return null
      return msgList.find(m => m.tempId === tempId)
    },

    /**
     * 通过 tempId 更新消息
     */
    updateMessageByTempId(sessionId, tempId, updates) {
      console.log('[ChatStore] updateMessageByTempId 调用:', { sessionId, tempId, updates })
      
      if (!sessionId || !tempId) {
        console.warn('[ChatStore] updateMessageByTempId 参数无效:', { sessionId, tempId })
        return false
      }
      
      const msgList = this.messages[sessionId]
      if (!msgList) {
        console.warn('[ChatStore] updateMessageByTempId 找不到会话消息列表:', sessionId)
        console.log('[ChatStore] 所有会话:', Object.keys(this.messages))
        return false
      }
      
      const index = msgList.findIndex(m => m.tempId === tempId)
      if (index === -1) {
        console.warn('[ChatStore] updateMessageByTempId 找不到消息:', { 
          sessionId, 
          tempId,
          messageCount: msgList.length,
          allTempIds: msgList.map(m => m.tempId)
        })
        return false
      }
      
      console.log('[ChatStore] 找到消息，准备更新:', {
        index,
        oldMsg: msgList[index],
        updates
      })
      
      // 合并更新
      msgList[index] = { ...msgList[index], ...updates }
      
      console.log('[ChatStore] 消息已更新:', msgList[index])
      return true
    },

    /**
     * 通过 messageId 更新消息
     */
    updateMessageById(sessionId, messageId, updates) {
      if (!sessionId || !messageId) return false
      const msgList = this.messages[sessionId]
      if (!msgList) return false
      
      const index = msgList.findIndex(m => m.messageId === messageId)
      if (index === -1) return false
      
      // 合并更新
      msgList[index] = { ...msgList[index], ...updates }
      return true
    },

    incrementUnread(count = 1) {
      const value = Number(count) || 0
      this.unreadCount = Math.max(0, this.unreadCount + value)
    },

    decrementUnread(count = 1) {
      const value = Number(count) || 0
      this.unreadCount = Math.max(0, this.unreadCount - value)
    },

    resetUnread() {
      this.unreadCount = 0
      const current = this.sessions.find((item) => item.sessionId === this.currentSessionId)
      if (current) current.unread = 0
    },

    setFloatingPosition(position) {
      if (!position) return
      if (typeof position.right === 'number') this.floatingPosition.right = Math.max(0, position.right)
      if (typeof position.bottom === 'number') this.floatingPosition.bottom = Math.max(0, position.bottom)
    }
  }
})

export default useChatStore
export { buildSessionId }

